import { drawerConfig, drawerTitle, drawerVisible } from "./drawer";
import { searchConfig } from "./search";
import { tablePage, tableConfig, tableData, tableLoading } from "./table";
import {
  operateType,
  merchantList,
  queryParams,
  tabIndex,
  drawerFormState,
} from "./store";
import { merchant_id } from "../chart/store";
import { handleSearchTime } from "@userList/search";
export const channelServername = ref<string>("");
export const fetchList = async () => {
  try {
    handleSearchTime(["start_date", "end_date"], queryParams, "YYYY-MM-DD");
    tableData.value.length = 0;
    tableLoading.value = true;
    const res = await channelApi.list.queryList({
      page: tablePage.current,
      page_size: tablePage.pageSize,
      ...queryParams,
    });
    tableData.value = res?.data?.list ?? [];
    tablePage.total = res?.data?.attributes?.total ?? 0;
  } catch (error: any) {
    message.error(error.message);
  } finally {
    tableLoading.value = false;
  }
};
export const refreshTable = async (searchParams: any = {}) => {
  tablePage.current = 1;
  initObjAttr(queryParams, searchParams);
  await fetchList();
};
export let tmp_proxy: any = null;
export let tmp_emit: any = null;
export const showDrawer = () => (drawerVisible.value = true);
export const handleAction = async ({ record, type }: any) => {
  operateType.value = type;
  switch (trimAll(type)) {
    case "add":
      drawerTitle.value = $t("base.addChannel");
      showDrawer();
      Object.keys(drawerFormState).forEach((key: any) => {
        drawerFormState[key] = void 0;
      });
      drawerFormState.status = 0;
      drawerFormState.servername = channelServername.value;
      break;
    case "data":
      tabIndex.value = 1;
      merchant_id.value = record.merchant_uid;
      tmp_emit("change", 1);
      break;
    case "update":
      drawerTitle.value = $t("base.editChannel");
      showDrawer();
      Object.keys(drawerFormState).forEach((key: any) => {
        drawerFormState[key] = record[key] ?? drawerFormState[key];
      });
      drawerFormState.editId = record.id;
      drawerFormState.merchant_uid = record.merchant_uid || void 0;
      break;
    case "delete":
      tmp_proxy.$confirm({
        closable: true,
        maskClosable: true,
        icon: null,
        title: () => <>{$t("base.delete")}</>,
        style: {
          top: "30%",
        },
        content: (
          <>
            {$t("channel0")}
            {record.name}
            {$t("channel1")}
            {record.name}
            {$t("channel2")}
          </>
        ),
        onOk: async () => {
          await channelApi.list.delete({
            editId: record.id,
          });
          refreshTable();
          message.success($t("base.deleteSuccess"));
        },
      });
      break;
    case "update->status":
      tmp_proxy.$confirm({
        closable: true,
        icon: null,
        maskClosable: true,
        title: () => <>{$t("base.editBusinessState")}</>,
        style: {
          top: "30%",
        },
        content: (
          <>
            {record.status === 0
              ? `${$t("channel3")} “${record.name}” ${$t("channel4")}`
              : `${$t("channel3")} “${record.name}” ${$t("channel5")}`}
          </>
        ),
        onOk: async () => {
          await channelApi.list.updateStatus({
            editId: record.id,
          });
          message.success($t("base.updateSucess"));
          fetchList();
        },
      });
      break;
  }
};
export const fetchCHannelDict = async () => {
  try {
    tableLoading.value = true;
    const res: any = await channelApi.list.queryChanelDict();
    if (res.code != 200) return message.error(res.message);
    channelServername.value = res.data.servername;
    merchantList.value = res.data.merchantUser?.map((item: any) => ({
      value: item.id,
      label: item.name,
    }));
  } catch (error: any) {
    message.error(error.message);
  } finally {
    tableLoading.value = false;
  }
};
export default defineComponent({
  emits: ["change"],
  setup(props, { attrs, emit, expose, slots }) {
    const { proxy } = reactive<any>(getCurrentInstance());
    tmp_emit = emit;
    tmp_proxy = proxy;
    const defineSearch = searchConfig();
    const defineDrawer = drawerConfig();
    const defineTable = tableConfig();
    watch(
      () => sysZone.value,
      () => fetchList()
    );
    const initPage = () => {
      fetchList();
      fetchCHannelDict();
    };
    expose({
      initPage,
    });
    return () => (
      <>
        <s-design
          defineTable={defineTable}
          defineSearch={defineSearch}
          defineDrawer={defineDrawer}
        />
      </>
    );
  },
});
